package com.eastedu.util;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

/**
 * The type List utils.
 *
 * @author ZHISHUAI.ZHANG
 */
public class ListUtils {

    private ListUtils() {
    }

    /**
     * Find prev element t.
     *
     * @param <T>    the type parameter
     * @param list   the list
     * @param target the target
     * @return the t
     */
    public static <T> T findPrevElement(List<T> list, T target) {
        int index = list.indexOf(target);
        if (index > 0) {
            return list.get(index - 1);
        } else {
            return null;
        }
    }

    /**
     * Find element t.
     *
     * @param <T>       the type parameter
     * @param list      the list
     * @param predicate the predicate
     * @return the t
     */
    public static <T> T findElement(List<T> list, Predicate<T> predicate) {
        for (T element : list) {
            if (predicate.test(element)) {
                return element;
            }
        }
        return null;
    }

    /**
     * All elements equal boolean.
     *
     * @param list the list
     * @return the boolean
     */
    public static boolean allElementsEqual(List<?> list) {
        if (list == null || list.isEmpty()) {
            return true;
        }

        Object firstElement = list.get(0);
        return list.stream().allMatch(element -> element.equals(firstElement));
    }

    /**
     * Gets last ten elements.
     *
     * @param <T>  the type parameter
     * @param list the list
     * @return the last ten elements
     */
    public static <T> List<T> getLastElements(List<T> list) {
        return getLastElements(list, 10);
    }

    /**
     * Gets last elements.
     *
     * @param <T>   the type parameter
     * @param list  the list
     * @param count the count
     * @return the last elements
     */
    public static <T> List<T> getLastElements(List<T> list, Integer count) {
        List<T> lastTenElements = new ArrayList<>();
        int size = list.size();
        if (size <= count) {
            return new ArrayList<>(list);
        } else {
            for (int i = size - count; i < size; i++) {
                lastTenElements.add(list.get(i));
            }
            return lastTenElements;
        }
    }

}
